package org.zxp.onedoteight;

import org.junit.Test;

import java.util.Optional;

/**
 * @program: effectiveJava
 * @description:
 * @author: X-Pacific zhang
 * @create: 2020-03-12 17:52
 **/
public class OptionalTest {
    @Test
    public void test1(){
        Stu s1 = null;
        Stu s2 = new Stu("zxp",10);
        //会直接报错
//        Optional<Stu> optionalStu = Optional.of(s1);
        Optional<Stu> optionalStu = Optional.ofNullable(s1);
        if(optionalStu.isPresent()){
            System.out.println(optionalStu.get());
        }else{
            //不能get，否则报错
            System.out.println("对象为空");
        }
    }


    @Test
    public void testMname(){
        Stu stu = new Stu("zxp",33);
        String name = Optional.ofNullable(stu).map(u-> u.getName()).get();
        Stu stu2 = null;
        Optional.ofNullable(stu2).orElse(new Stu("zxp",33)).getName();
    }

    @Test
    public void test2(){
        Stu s1 = null;
        Stu s2 = new Stu("zxp",10);
        //如果s1为null则返回兜底数据s2，注意这里返回的是T
        Stu s3 = Optional.ofNullable(s1).orElse(s2);
        System.out.println(s3);
    }


    private static class Stu{
        private String name;
        private int age;

        public Stu(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Stu{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
